<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-upload name="file" :showUploadList="false" :action="ossAction" :headers="tokenHeader" :beforeUpload="beforeUpload" @change="handleChange">
          <a-button type="primary" preIcon="ant-design:upload-outlined">OSS文件上传</a-button>
        </a-upload>
        <!-- <a-upload
          name="file"
          :showUploadList="false"
          :action="minioAction"
          :headers="tokenHeader"
          :beforeUpload="beforeUpload"
          @change="handleChange"
        >
          <a-button type="primary" preIcon="ant-design:upload-outlined">MINIO文件上传</a-button>
        </a-upload> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="system-ossfile" setup>
  //ts语法
  import { ref, computed, unref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { columns, searchFormSchema } from './ossfile.data';
  import { list, deleteFile, getOssUrl, getMinioUrl } from './ossfile.api';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getToken } from '/@/utils/auth';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import Clipboard from 'clipboard';
  import Base64 from 'crypto-js/enc-base64';
  import sha1 from 'crypto-js/sha1';
  import CryptoJS from 'crypto-js';
  import { getHeaders } from '/@/utils/common/compUtils';

  const { createMessage, createConfirm } = useMessage();
  const glob = useGlobSetting();
  const tokenHeader = getHeaders();
  //注册table数据
  const [registerTable, { reload }] = useTable({
    api: list,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    clickToRowSelect: false,
    bordered: true,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    beforeFetch: (params) => {
      return Object.assign({ column: 'createTime', order: 'desc' }, params);
    },
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
  });
  /**
   * 上传url
   */
  const ossAction = computed(() => `${getOssUrl}`);
  const minioAction = computed(() => `${getMinioUrl}`);

  /**
   * 预览
   */
  function handleView(record) {
    if (record && record.url) {
      //TODO 这种地址需不需要拿出去？
      // console.log('glob.onlineUrl', glob.viewUrl);
      let url = record.url;
      if (glob.viewUrl) {
        let trans = CryptoJS.enc.Utf8.parse(decodeURIComponent(record.url));
        let encrypted = CryptoJS.enc.Base64.stringify(trans);
        url = `${glob.viewUrl}?url=` + encodeURIComponent(encrypted);
      }
      window.open(url, '_blank');
    }
  }

  /**
   * 下载
   */
  function handleDownload(record) {
    if (record && record.url) {
      //downloadFile(record.url);
      var xhr = new XMLHttpRequest();
      xhr.open('GET', record.url, true);
      xhr.responseType = 'blob'; //web-portal
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if (xhr.status == 200) {
            var blod = this.response;
            console.log(blod);
            // var src = URL.createObjectURL(blod);
            var eleLink = document.createElement('a');
            eleLink.download = record.name;
            eleLink.href = URL.createObjectURL(blod);
            document.body.appendChild(eleLink);
            eleLink.click();
          }
        }
      };
      xhr.send();
    }
  }

  /**
   * 复制
   */
  function handleCopy(record) {
    if (record && record.url) {
      let url = record.url;
      let previewurl = record.url;
      if (glob.viewUrl) {
        let trans = CryptoJS.enc.Utf8.parse(decodeURIComponent(previewurl));
        let encrypted = CryptoJS.enc.Base64.stringify(trans);
        previewurl = `${glob.viewUrl}?url=` + encodeURIComponent(encrypted);
      }
      let content =
        '<strong>文件名：</strong>' +
        record.name +
        '<br/><br/><strong>文件下载地址：</strong>' +
        url +
        '<br/><br/><strong>文件预览地址：</strong>' +
        previewurl;
      createConfirm({
        iconType: 'info',
        width: 500,
        title: `文件链接`,
        content: content,
        closable: true,
        maskClosable: true,
        cancelText: '复制文件下载地址',
        okText: '复制文件预览地址',
        cancelButtonProps: {
          class: 'copy-this-url',
          'data-clipboard-text': url,
        },
        okButtonProps: {
          class: 'copy-this-previewurl',
          'data-clipboard-text': previewurl,
        },
        onOk: () => {
          const clipboard = new Clipboard('.copy-this-previewurl');
          clipboard.on('success', () => {
            clipboard.destroy();
            createMessage.success('复制文件预览地址成功');
          });
          clipboard.on('error', () => {
            createMessage.error('该浏览器不支持自动复制');
            clipboard.destroy();
          });
        },
        onCancel: () => {
          const clipboard = new Clipboard('.copy-this-url');
          clipboard.on('success', () => {
            clipboard.destroy();
            createMessage.success('复制文件下载地址成功');
          });
          clipboard.on('error', () => {
            createMessage.error('该浏览器不支持自动复制');
            clipboard.destroy();
          });
        },
      });
    }
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteFile({ id: record.id }, reload);
  }

  /**
   * 上传前事件
   */
  function beforeUpload(file) {
    var fileType = file.type;
    if (fileType === 'image') {
      if (fileType.indexOf('image') < 0) {
        createMessage.warning('请上传图片');
        return false;
      }
    } else if (fileType === 'file') {
      if (fileType.indexOf('image') >= 0) {
        createMessage.warning('请上传文件');
        return false;
      }
    }
    return true;
  }

  /**
   * 文件上传事件
   */
  function handleChange(info) {
    console.log('wang-file', info);
    if (info.file.status === 'done') {
      if (info.file.response.success) {
        reload();
        createMessage.success(`${info.file.name} 上传成功!`);
      } else {
        createMessage.error(`${info.file.response.msg}`);
      }
    } else if (info.file.status === 'error') {
      createMessage.error(`${info.file.response.msg}`);
    }
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '预览',
        onClick: handleView.bind(null, record),
      },
      {
        label: '下载',
        onClick: handleDownload.bind(null, record),
      },
      {
        label: '复制',
        onClick: handleCopy.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
</script>

<style scoped></style>
